package com.bsoft.gol.hcs.clinical.dao;

import com.bsoft.gol.hcs.clinical.bean.req.BaseWmDiseasesRequest;
import com.bsoft.gol.hcs.clinical.bean.req.QueryDiagnosticListRequest;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.spring.boot.annotation.SsdevDao;
import ctd.util.annotation.RpcService;
import ctd.util.converter.ConversionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import pcn.diagnosis.BaseWmDiseases;
import com.bsoft.gol.hcs.specialist.bean.request.QueryOperativeListRequest;
import com.bsoft.gol.hcs.specialist.bean.response.OperativeListResp;
import com.bsoft.gol.hcs.utils.CommonUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SsdevDao( serviceId = "baseWmDiseasesDAOService")
public abstract class BaseWmDiseasesDAO extends HibernateSupportDelegateDAO<BaseWmDiseases> {


    public List<BaseWmDiseases> queryDiagnosticList(final QueryDiagnosticListRequest request) {
        HibernateStatelessResultAction<List<BaseWmDiseases>> action = new AbstractHibernateStatelessResultAction<List<BaseWmDiseases>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getDiagnosticInformationStringBuffer(request);
                SQLQuery sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                int first = request.getPageNo() > 0 ? (request.getPageNo() - 1) * request.getPageSize() : 0;
                sqlQuery.setFirstResult(first);
                sqlQuery.setMaxResults(request.getPageSize());
                sqlQuery.addEntity(BaseWmDiseases.class);
                setResult(sqlQuery.list());
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    public BigInteger queryDiagnosticListTotal(final QueryDiagnosticListRequest request) {
        HibernateStatelessResultAction<BigInteger> action = new AbstractHibernateStatelessResultAction<BigInteger>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("select COUNT(0) from ( " + getDiagnosticInformationStringBuffer(request) + " ) t");
                Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                List list = sqlQuery.list();
                if (list.size() == 1) {
                    Object o = list.get(0);
                    BigInteger count = (BigInteger) o;
                    setResult(count);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }


    public List<OperativeListResp> queryDiagnosticListByPinYin(final QueryOperativeListRequest request) {
        HibernateStatelessResultAction<List<OperativeListResp>> action = new AbstractHibernateStatelessResultAction<List<OperativeListResp>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getDiagnosticInformationStringByPinYin(request);
                SQLQuery sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                int first = request.getPageNo() > 0 ? (request.getPageNo() - 1) * request.getPageSize() : 0;
                sqlQuery.setFirstResult(first);
                sqlQuery.setMaxResults(request.getPageSize());
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                List<OperativeListResp> listResps = new ArrayList<>();
                for (Map map : dbList) {
                    listResps.add(ConversionUtils.convert(map, OperativeListResp.class));
                }
                setResult(listResps);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private StringBuffer getDiagnosticInformationStringBuffer(QueryDiagnosticListRequest request) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select diseases_id, diseases_code_type, diseases_code, diseases_name, pinyin_code, sex_restriction_flag, " +
                "cure_flag, improve_flag, no_healing_flag, death_flag, other_flag, control_mode, upper_age_limit, lower_age_limit, " +
                "delete_flag, delete_dt, delete_user, extra_code, statistics_code, remark from base_wm_diseases WHERE " +
                "  delete_flag = '0' and diseases_code <> '—'  ");
        if (StringUtils.isNotEmpty(request.getKeyWord())) {
            stringBuffer.append(" and pinyin_code like '" + request.getKeyWord() + "%'" +
                    " OR diseases_name like '" + request.getKeyWord() + "%'");
        }
        return stringBuffer;
    }

    private StringBuffer getWesternMedicineDiagnosisStringBuffer(BaseWmDiseasesRequest request) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select diseases_id, diseases_code_type, diseases_code, diseases_name, pinyin_code, sex_restriction_flag, " +
                "cure_flag, improve_flag, no_healing_flag, death_flag, other_flag, control_mode, upper_age_limit, lower_age_limit, " +
                "delete_flag, delete_dt, delete_user, extra_code, statistics_code, remark from base_wm_diseases WHERE " +
                "  delete_flag = '0' and diseases_code <> '—'  ");
        if (CommonUtils.isNotEmpty(request.getDiseasesName())) {
            stringBuffer.append(" and diseases_name like '" + request.getDiseasesName() + "%' ");
        }
        if (CommonUtils.isNotEmpty(request.getDiseasesCode())) {
            stringBuffer.append(" and diseases_code like '" + request.getDiseasesCode() + "%' ");
        }
        if (CommonUtils.isNotEmpty(request.getPinyinCode())) {
            stringBuffer.append(" and pinyin_code like '" + request.getPinyinCode() + "%' ");
        }
        return stringBuffer;
    }

    @DAOMethod(sql = " from BaseWmDiseases where diseasesId =:diseasesId ")
    public abstract BaseWmDiseases getBaseWmDiseases(@DAOParam("diseasesId") int diseasesId);

    @RpcService
    @DAOMethod(sql = " from BaseWmDiseases where diseasesCode =:diseasesCode ")
    public abstract BaseWmDiseases getBaseWmDiseasesByDiseasesCode(@DAOParam("diseasesCode") String diseasesCode);

    public List<BaseWmDiseases> queryWesternMedicine(final BaseWmDiseasesRequest request) {
        HibernateStatelessResultAction<List<BaseWmDiseases>> action = new AbstractHibernateStatelessResultAction<List<BaseWmDiseases>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getWesternMedicineDiagnosisStringBuffer(request);
                SQLQuery sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                int first = request.getPageNo() > 0 ? (request.getPageNo() - 1) * request.getPageSize() : 0;
                sqlQuery.setFirstResult(first);
                sqlQuery.setMaxResults(request.getPageSize());
                sqlQuery.addEntity(BaseWmDiseases.class);
                setResult(sqlQuery.list());
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    public List<BaseWmDiseases> findWesternMedicine(final BaseWmDiseasesRequest request) {
        HibernateStatelessResultAction<List<BaseWmDiseases>> action = new AbstractHibernateStatelessResultAction<List<BaseWmDiseases>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getWesternMedicineDiagnosisStringBuffer(request);
                SQLQuery sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                int first = request.getPageNo() > 0 ? (request.getPageNo() - 1) * request.getPageSize() : 0;
                sqlQuery.setFirstResult(first);
                sqlQuery.setMaxResults(request.getPageSize());
                sqlQuery.addEntity(BaseWmDiseases.class);
                setResult(sqlQuery.list());
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }


    private StringBuffer getDiagnosticInformationStringByPinYin(QueryOperativeListRequest request) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(" select diseases_code relateRecordId, diseases_name   relateName  from base_wm_diseases WHERE  delete_flag = '0'  ");
        if (StringUtils.isNotEmpty(request.getPyCode())) {
            stringBuffer.append(" and pinyin_code like '" + request.getPyCode().toUpperCase() + "%' ");
        }
        return stringBuffer;
    }

    public BigInteger queryWesternMedicineDiagnosisTotal(final BaseWmDiseasesRequest request) {
        HibernateStatelessResultAction<BigInteger> action = new AbstractHibernateStatelessResultAction<BigInteger>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("select COUNT(0) from ( " + getWesternMedicineDiagnosisStringBuffer(request) + " ) t");
                Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                List list = sqlQuery.list();
                if (list.size() == 1) {
                    Object o = list.get(0);
                    BigInteger count = (BigInteger) o;
                    setResult(count);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
    @DAOMethod(sql = " from BaseWmDiseases order by diseases_id desc limit 1 ")
    public abstract BaseWmDiseases getMaxBaseWmDiseases();

    @DAOMethod(sql = " from BaseWmDiseases order by diseases_id desc limit 1 ")
    public abstract void removeAll();
}
